package com.highspeed.bdk.controller.security.resource;

import com.bianmaba.spring.data.jpa.domain.PageableRequest;
import com.bianmaba.spring.mvc.controller.CrudController;
import com.bianmaba.spring.mvc.method.support.annotations.EntityParam;
import com.bianmaba.spring.mvc.method.support.annotations.JSON;
import com.bianmaba.spring.mvc.method.support.annotations.MapParam;
import com.highspeed.bdk.bean.entity.security.Resource;
import com.highspeed.bdk.bean.entity.security.Role;
import com.highspeed.bdk.service.security.resource.IResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.*;

/**
 * Created by cwx183898 on 2017/8/10.
 */
@RestController
@RequestMapping(value = {"management/security/resource"})
public class MGTResourceController extends CrudController<Resource, String> {

    @Autowired
    private IResourceService service;

    @Override
    protected IResourceService getService() {
        return service;
    }

    @Override
    @JSON(excludeProperties = "data.*\\.users\\.resources,data.*\\.roles\\.resources")
    public Resource save(@EntityParam Resource entity) {
        return super.save(entity);
    }

    @Override
    @JSON(excludeProperties = "data.*\\.roles\\.resources,data.*\\.roles\\.users")
    public Resource getById(String id) {
        return super.getById(id);
    }

    @JSON(excludeProperties = "data.*\\.roles")
    public Page<Resource> query(@MapParam LinkedHashMap<String, Object> params, @EntityParam PageableRequest pageable) {
        Page<Resource> page = super.query(params, pageable);
        return page;
    }


    @RequestMapping({"/all_resources"})
    public Map<String, List<String>> getAllResources(Principal principal) {
        Map<String, List<String>> data = new HashMap<String, List<String>>();
        List<Resource> resources = service.query();
        for (Resource resource : resources) {
            List<String> list = new ArrayList<String>();
            List<Role> roles = resource.getRoles();
            if (roles != null) {
                for (Role role : roles) {
                    list.add(role.getId());
                }
            }
            data.put(resource.getUrl(), list);
        }
        return data;
    }
}
